﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;

class Tracer
{
    const string serverUrl = "https://gamelogs.snowcattle.com/gamelogs";
    const string seperator = "|";

    class TimeStamp
    {
        public static DateTime originTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public static double Now
        {
            get { return (DateTime.Now - originTime).TotalMilliseconds / 1000; }
        }
    }

    static string GUID = "";
    static string versionInfo = "";
    private static List<string> logs;

    static Tracer()
    {
        bool isNewPlayer = false;
        GUID = PlayerPrefs.GetString("TracerGUID", "");
        if (GUID == "")
        {
            GUID = Guid.NewGuid().ToString();
            PlayerPrefs.SetString("TracerGUID", GUID);
            PlayerPrefs.Save();
            isNewPlayer = true;
        }

        versionInfo = String.Format("{0},{1},{2},{3}",
            Application.identifier,
            Application.platform,
            Application.version,
            GUID
        );
        
        var savedLogs = PlayerPrefs.GetString("savedLogs", "");
        if (savedLogs.Length > 0)
        {
            logs = new List<string>(savedLogs.Split(seperator.ToCharArray()));
            PlayerPrefs.SetString("savedLogs", "");
        }
        else
        {
            logs = new List<string>();
        }
        
        if (isNewPlayer)
        {
            Trace("new_player");
        }
    }

    // bundle-id, platform, version, GUID, timestamp, eventId, eventId
    public static void Trace(string eventId, string eventInfo = "")
    {
#if !UNITY_EDITOR
        var log = String.Format("{0},{1},{2}",
            (int) TimeStamp.Now,
            eventId,
            eventInfo
        );
        // Debug.Log(log);
        logs.Add(log);
#endif
    }

    public static IEnumerator Send()
    {
        if (logs.Count == 0)
        {
            yield break;
        }

        var data = String.Join(seperator, logs);
        logs.Clear();


        UnityWebRequest request = new UnityWebRequest();
        request.url = serverUrl;
        
        // add version info
        var sendData = String.Format("{0}{1}{2}", versionInfo, seperator, data);
        request.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(sendData));
        
        request.downloadHandler = new DownloadHandlerBuffer();
        request.method = UnityWebRequest.kHttpVerbPOST;
        yield return request.SendWebRequest();
        
        if (request.error != null)
        {
            logs.InsertRange(0, data.Split(seperator.ToCharArray()));
            request.Dispose();
        }
    }

    public static void SaveToLocalStorage()
    {
        PlayerPrefs.SetString("savedLogs", logs.Count > 0 ? String.Join(seperator, logs) : "");
    }
}